package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import com.atguigu.lease.model.enums.ItemType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author Marco
 * @Description
 * @date 2025/7/24 19:28
 * @email 3293336923@qq.com
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
//       spring 类型到  目标类型  的 转换器
        return new Converter<String, T>() {
//            前端传递过来的 具体编码值，返回对应的枚举类型字符串
            @Override
            public T convert(String code) {

//                获取目标类所有的枚举实例
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants) {
                    if (enumConstant.getCode().equals(Integer.valueOf(code))) {
                        return enumConstant;
                    }
                }
                throw new IllegalArgumentException("code:" + code + "非法！");
            }
        };
    }
}
